package com.yusys.jin.blog.serviceimpl;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.yusys.jin.blog.entity.GameRole;
import com.yusys.jin.blog.ex.InsertException;
import com.yusys.jin.blog.ex.checkRoleException;
import com.yusys.jin.blog.ex.roleAlreadyExsitException;
import com.yusys.jin.blog.mapper.GameRoleMapper;
import com.yusys.jin.blog.service.IGameRoleService;

@Service
public class GameRoleServiceImpl implements IGameRoleService {
    @Autowired
    GameRoleMapper mapper;
    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    private SimpleDateFormat sdf1 = new SimpleDateFormat("yyyyMMdd");

    @Override
    public void addRole(GameRole role, String userName) {
        //检查上传数据合法性
        String checkMessage = checkRole(role);
        if (checkMessage != "") {
            throw new checkRoleException(checkMessage);
        }
        //检查上传的角色信息是否已存在
        GameRole data = getRoleByAreaCDAndRoleName(role.getRoleName(), role.getServerCD());
        System.out.println(data);
        if (data != null) {
            throw new roleAlreadyExsitException("该服务器已存在此角色，请确认");
        }
        //封装四项日志
        Date now = new Date();
        String date = sdf.format(now);
        role.setCreatedTime(date);
        role.setCreatedUser(userName);
        role.setModifiedTime(date);
        role.setModifiedUser(userName);
        //执行插入操作
        insertRole(role);


    }

    private String checkRole(GameRole role) {
        //检查上传字段是否合法
        Integer now = Integer.parseInt(sdf1.format(new Date()));
        String checkMessage = "";
        if (role.getRoleName() == null) return "角色名不能为空";
        if (role.getRoleName().length() > 12) return "角色名长度不能大于12";
        if (role.getLevel() > 120 || role.getLevel() < 0) return "角色等级不合法";
        if (Integer.parseInt(role.getRoleBirthday()) < 20150228 || Integer.parseInt(role.getRoleBirthday()) > now)
            return "角色创建时间不正确";
        if (role.getRem().length() > 255) return "备注字数超过最大字数255";
        return checkMessage;
    }

    @Override
    public List<GameRole> queryRoles(Integer uid) {
        // TODO Auto-generated method stub
        return null;
    }

    private List<GameRole> getRolesByUid(Integer uid) {
        return mapper.queryRoles(uid);
    }

    private void insertRole(GameRole role) {
        Integer rows = mapper.insertGameRole(role);
        if (rows != 1) {
            throw new InsertException("角色插入异常，请联系管理员处理");
        }
    }

    private GameRole getRoleByAreaCDAndRoleName(String ServerCd, String RoleName) {
        System.out.println(ServerCd + "    " + RoleName);
        return mapper.queryRoleByNameAndServerCD(ServerCd, RoleName);
    }


}
